//
//  CompoundGoodsList.swift
//  LeGou
//
//  Created by lxm on 2022/11/10.
//

import UIKit

class CompoundStoreList: ZMViewController, UITableViewDelegate, UITableViewDataSource, ListRequestObjct {

    //MARK:--------------------属性--------------------
    // ("合成中", 0), ("已合成", 1), ("已失效", 2)
    var type = 0
    
    var listData = [ListModel]()
    var page = 1
    var pageSize = 10
    var refreshScrollView : UIScrollView {
        tableView
    }
    //MARK:--------------------UI控件--------------------
    @IBOutlet weak var tableView: UITableView!
    
    
    //MARK:--------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
        tableView.mj_header?.beginRefreshing()
    }
    //MARK:--------------------UI--------------------
    func setUI() {
        title = "合成详情"
        tableView.delegate = self
        tableView.dataSource = self
        
        tableView.zm.register(nibName: "CompoundStoreListCell", reuserId: "CompoundStoreListCell")
        tableView.estimatedRowHeight = 156
        tableView.rowHeight = UITableView.automaticDimension
        tableView.contentInset = UIEdgeInsets(top: 8, left: 0, bottom: 0, right: 0)
        
        addRefresh(scrollView: tableView) { [weak self] refresh in
            guard let self = self else {return}
            if refresh {
                self.page = 1
            }
            self.loadList()
        }
        addNodataScrollView(scrollView: tableView)
        emptyTitle = "暂无数据"
        emptyImg = "nodata"
    }
    func addConstraints() {
        
    }
    
    //MARK:--------------------methods--------------------
    func bindAction() {
        
    }
    
    func loadList() {
        let pa = ["limit" : pageSize, "page" : page, "status" : type]
        ZMUtil.listRequest(type: ListModel.self, api: AuctionAPI.compoundList(pa)) { resp in
            self.listRequest(resp)
        }
    }
    
    // 合成
    func compound(conflateId : Int) {
        ZMToast.showActivity()
        AuctionAPI.compound(["conflateId" : conflateId]).rxRequest(type: AuctionModels.CompoundResult.self).subscribe(onNext:{ [unowned self] resp in
            ZMToast.hiddenActivity()
            if resp.giveQuantity == 0 {
                // 无商品
                let v = ZMUtil.loadNibViewFullScreen(nibName: CompoundSuccessNoGoodsView.self)
                v.price.attributedText = "".zm.append(str: "¥", attri: ["f" : "14s"]).zm.append(str: "\(resp.rewardAmount.zm.toString(keep: 4))")
                v.sureBtn.rx.tap.subscribe(onNext:{ [unowned self, weak v] r in
                    v?.removeFromSuperview()
                    self.tableView.mj_header?.beginRefreshing()
                }).disposed(by: v.disposeBag)
                APPWindow?.addSubview(v)
            } else {
                let v = ZMUtil.loadNibViewFullScreen(nibName: CompoundSuccessView.self)
                v.count.text = "\(resp.giveQuantity)"
                v.price.attributedText = "".zm.append(str: "¥", attri: ["f" : "14s"]).zm.append(str: "\(resp.rewardAmount.zm.toString(keep: 4))")
                v.sureBtn.rx.tap.subscribe(onNext:{ [unowned self, weak v] r in
                    let vc = VIPOrderDetail()
                    vc.orderNo = resp.orderId
                    v?.removeFromSuperview()
                    self.tableView.mj_header?.beginRefreshing()
                    self.navigationController?.pushViewController(vc, animated: true)
                }).disposed(by: v.disposeBag)
                APPWindow?.addSubview(v)
            }
        }).disposed(by: disposeBag)
    }

    //MARK:--------------------delegate--------------------
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        tableView.mj_footer?.isHidden = listData.count == 0
        return listData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CompoundStoreListCell") as! CompoundStoreListCell
        let data = listData[indexPath.row]
        cell.img.zm.setImage(urlStr: data.image)
        cell.name.text = data.productName
        var p = Float(data.currentTotal) / Float(data.conflateTotal)
        if p > 1 {
            p = 1
        }
        cell.progress.progress = p
        cell.percent.text = "\(Int(p * 100))%"
        cell.progressLabel.text = "\(data.currentTotal)/\(data.conflateTotal)"
        cell.leftBtn.layer.borderColor = UIColor.zm.color333333().cgColor
        cell.leftBtn.setTitleColor(UIColor.zm.color333333(), for: .normal)
        cell.leftBtn.setTitle("查看详情", for: .normal)
        
        cell.rightBtn.layer.borderWidth = 0
        cell.rightBtn.setTitleColor(.white, for: .normal)
        cell.rightBtn.backgroundColor = Style.mainColor
        
        if p == 1 {
            cell.rightBtn.backgroundColor = Style.mainColor
        } else {
            cell.rightBtn.backgroundColor = UIColor.zm.colorCCCCCC()
        }
        
        if type == 0 {
            cell.rightBtn.isHidden = true
            cell.rightBtn.setTitle("立即合成", for: .normal)
            cell.rightBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
                self.compound(conflateId: data.id)
            }).disposed(by: cell.disposeBag)
        } else if type == 1 {
            cell.rightBtn.isHidden = data.orderId.count == 0
            cell.rightBtn.setTitle("赠送商品订单", for: .normal)
            cell.rightBtn.layer.borderWidth = 0.5
            cell.rightBtn.layer.borderColor = Style.mainColor.cgColor
            cell.rightBtn.setTitleColor(Style.mainColor, for: .normal)
            cell.rightBtn.backgroundColor = .white
            
            cell.rightBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
                let detail = VIPOrderDetail()
                detail.orderNo = data.orderId
                self.navigationController?.pushViewController(detail, animated: true)
            }).disposed(by: cell.disposeBag)
        } else if type == 2 {
            cell.rightBtn.isHidden = true
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let data = listData[indexPath.row]

        if type == 0 {
            let vc = CompoundGoodsList()
            vc.type = type
            vc.conflateId = data.id
            vc.maxCount = data.conflateTotal
            vc.listchangeCallBack = { [weak self] in
                guard let self = self else{return}
                self.tableView.mj_header?.beginRefreshing()
            }
            self.navigationController?.pushViewController(vc, animated: true)
        } else {
            let vc = CompoundOrderDetail()
            vc.conflateId = data.id
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
//
//        let v = ZMUtil.loadNibViewFullScreen(nibName: CompoundSuccessNoGoodsView.self)
//        APPWindow?.addSubview(v)
    }
}


extension CompoundStoreList {
    class ListModel  : HandyJSON {
        required init(){}
        var conflateTotal = 0
        var currentTotal: Int = 0
        var id = 0
        var orderId = ""
        var productId: Int = 0
        var productName = ""
        var image = ""
    }
}
